package com.xbts.system.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xbts.common.core.domain.entity.SysUser;
import com.xbts.common.enums.EmailTypeEnum;
import com.xbts.common.exception.ServiceException;
import com.xbts.common.utils.StringUtils;
import com.xbts.system.domain.SysMessage;
import com.xbts.system.domain.dto.EmailSendDTO;
import com.xbts.system.service.ICnWeChatTemplateMsgService;
import com.xbts.system.service.ISysMessageService;
import com.xbts.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.xbts.system.mapper.SysUserAuthenticationMapper;
import com.xbts.system.domain.SysUserAuthentication;
import com.xbts.system.service.ISysUserAuthenticationService;
import com.xbts.common.utils.DateUtils;
import com.xbts.common.utils.SecurityUtils;

/**
 * 用户认证Service业务层处理
 * 
 * @author xbts
 * @date 2023-10-20
 */
@Service
public class SysUserAuthenticationServiceImpl  extends ServiceImpl<SysUserAuthenticationMapper, SysUserAuthentication> implements ISysUserAuthenticationService {


    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysMessageService sysMessageService;

    @Autowired
    private ICnWeChatTemplateMsgService cnWeChatTemplateMsgService;

    @Autowired
    private EmailSendService emailSendService;

    /**
     * 查询用户认证列表
     *
     * @param sysUserAuthentication 用户认证
     * @return 用户认证
     */
    @Override
    public List<SysUserAuthentication> selectSysUserAuthenticationList(SysUserAuthentication sysUserAuthentication) {
        QueryWrapper<SysUserAuthentication> queryWrapper = sysUserAuthentication.queryWrapper();
        return list(queryWrapper);
    }

    /**
     * 查询用户认证
     *
     * @param id 用户认证主键
     * @return 用户认证
     */
    @Override
    public SysUserAuthentication selectSysUserAuthenticationById(String id) {
        return getById(id);
    }

    /**
     * 新增用户认证
     *
     * @param sysUserAuthentication 用户认证
     * @return 结果
     */
    @Override
    public boolean insertSysUserAuthentication(SysUserAuthentication sysUserAuthentication) {

        SysUser user = userService.selectUserById(SecurityUtils.getUserId());
        Integer authentication = user.getAuthentication();
        if(authentication == 3){
            throw new ServiceException("资质审核中，请勿重复提交！");
        }
        sysUserAuthentication.setStatus(1);
        sysUserAuthentication.setCreateBy(SecurityUtils.getUserId().toString());
        sysUserAuthentication.setUserId(SecurityUtils.getUserId().toString());
        sysUserAuthentication.setNickName(user.getNickName());
        sysUserAuthentication.setType(user.getUserType().equals("01") ? 1 : 2);
        user.setAuthentication(3);
        userService.updateUserProfile(user);
        return save(sysUserAuthentication);
    }

    /**
     * 修改用户认证
     *
     * @param sysUserAuthentication 用户认证
     * @return 结果
     */
    @Override
    @Transactional
    public boolean updateSysUserAuthentication(SysUserAuthentication sysUserAuthentication) {
        sysUserAuthentication.setUpdateBy(SecurityUtils.getUserId().toString());
        sysUserAuthentication.setUpdateTime(DateUtils.getNowDate());
        Integer status = sysUserAuthentication.getStatus();
        SysUser user = userService.getUserInfo(Long.valueOf(sysUserAuthentication.getUserId()));

        String title = "认证" + (status == 2 ? "成功" : "失败") + "通知";
        String content = "";

        SysMessage message = new SysMessage();
        message.setUserIds(Collections.singletonList(Long.valueOf(sysUserAuthentication.getUserId())));
        message.setNoticeType(2);
        message.setNoticeTitle(title);
        String statusStr = "认证通过";
        if(status == 2){
            user.setAuthentication(1);
            user.setUserType(sysUserAuthentication.getType() == 1 ? "01" : "02");
            user.setAddress(sysUserAuthentication.getAddress());
            user.setAddressDetail(sysUserAuthentication.getAddressDetail());
            user.setCertificatePath(sysUserAuthentication.getCertificatePath());
            user.setNumber(sysUserAuthentication.getNumber());
            user.setRealName(sysUserAuthentication.getRealName());
            content = "【" + sysUserAuthentication.getRealName() + "】认证成功!";
        } else if(status == 3){
            if(StringUtils.isBlank(sysUserAuthentication.getRemake())){
                throw new ServiceException("请填写认证失败原因！");
            }
            user.setAuthentication(2);
            content = "【" + sysUserAuthentication.getRealName() + "】认证失败，失败原因为：" + sysUserAuthentication.getRemake();
            statusStr = "认证失败";
        } else {
            return false;
        }
        message.setIsAll(1);
        message.setNoticeContent(content);
        sysMessageService.addSysMessage(message);
        userService.updateUserProfile(user);
        cnWeChatTemplateMsgService.sendRealNameAuthenticationNotificationMsg(user.getUserId().toString(), DateUtils.getTime(), statusStr);

        // 发送邮件
        //获取用户邮箱地址
        String email = userService.getEmailByUserId(Long.valueOf(sysUserAuthentication.getUserId()));
        emailSendService.sendMessage(new EmailSendDTO(email, title, EmailTypeEnum.CONTRACT_INVALIDATION, sysUserAuthentication.getRealName(), (status == 2 ? "成功" : "失败")));
        return updateById(sysUserAuthentication);
    }

    /**
     * 批量删除用户认证
     *
     * @param ids 需要删除的用户认证主键
     * @return 结果
     */
    @Override
    public boolean deleteSysUserAuthenticationByIds(List<String> ids) {
        Long count = this.count(new LambdaQueryWrapper<SysUserAuthentication>()
                .in(SysUserAuthentication::getId, ids)
                .eq(SysUserAuthentication::getStatus, 1));
        if(count > 0){
            throw new ServiceException("订单需审核完成后才能删除！");
        }
        return removeBatchByIds(ids);
    }

    /**
     * 删除用户认证信息
     *
     * @param id 用户认证主键
     * @return 结果
     */
    @Transactional
    @Override
    public boolean deleteSysUserAuthenticationById(String id) {
      return removeById(id);
    }

}
